package com.airticketbooking.service.serviceImpl;

import cn.hutool.crypto.digest.MD5;
import com.airticketbooking.common.constant.JwtClaimsConstant;
import com.airticketbooking.common.constant.StatusConstant;
import com.airticketbooking.common.domain.PageQuery;
import com.airticketbooking.common.domain.R;
import com.airticketbooking.common.properties.JwtProperties;
import com.airticketbooking.common.utils.BeanUtils;
import com.airticketbooking.common.utils.JwtUtil;
import com.airticketbooking.common.utils.Md5Util;
import com.airticketbooking.common.utils.UserContext;
import com.airticketbooking.dto.UserDTO;
import com.airticketbooking.po.User;
import com.airticketbooking.vo.UserPageVO;
import com.airticketbooking.mapper.UserMapper;
import com.airticketbooking.service.UserService;
import com.airticketbooking.vo.UserVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * @author Mr.J
 * @version 1.0.0
 * @date 2024/11/11
 * @desc
 */

@Service
@RequiredArgsConstructor
@Transactional
public class UserServiceImpl implements UserService {


	private final UserMapper userMapper;

	private final JwtProperties jwtProperties;


	@Override
	public void add(User user) {

		user.setCreateDate(LocalDateTime.now());
		user.setStatus(1);
		userMapper.add(user);
	}

	@Override
	public void modify(UserDTO userDTO) {
		User user = new User();
		user.setUserId(UserContext.getUser().intValue());
		BeanUtils.copyProperties(userDTO, user);
		user.setUpdateDate(LocalDateTime.now());
		userMapper.update(user);
	}

	@Override
	public User getUserById(Integer userId) {

		return userMapper.getUserById(userId);
	}

	@Override
	public Page<UserPageVO> getUserByPage(PageQuery pageQuery) {

		PageHelper.startPage(pageQuery.getPageNo(), pageQuery.getPageSize());

		return userMapper.getUserByPage(pageQuery);
	}


	@Override
	public void openOrBanUser(Integer userId) {

		User user = userMapper.getUserById(userId);

		if (user == null) {
			throw new IllegalArgumentException("用户不存在");
		}

		Integer newStatus = StatusConstant.ENABLE;

		if (user.getStatus() == StatusConstant.ENABLE) {

			newStatus = StatusConstant.DISABLE;
		} else if (user.getStatus() == StatusConstant.DISABLE) {
			newStatus = StatusConstant.ENABLE;
		}

		user.setStatus(newStatus);
		user.setUpdateDate(LocalDateTime.now());
		userMapper.update(user);

	}

	@Override
	public void changePassword(String oldPassword, String newPassword, String rePassword) {

		if (!newPassword.equals(rePassword)) {
			throw new IllegalArgumentException("两次输入的密码不一致");
		}

		User user = userMapper.getUserById(UserContext.getUser().intValue());

		if (!user.getPassword().equals(Md5Util.getMD5String(oldPassword))) {
			throw new IllegalArgumentException("原密码错误");
		}


		//		对密码进行加密

		String md5Password = Md5Util.getMD5String(newPassword);

		user.setPassword(md5Password);
		user.setUpdateDate(LocalDateTime.now());

		userMapper.update(user);
	}

	@Override
	public void register(String username, String password) {


		User user = userMapper.getUserByUserName(username);

		if (user != null) {
			throw new IllegalArgumentException("用户名已存在");
		}

		String md5Password = Md5Util.getMD5String(password);


		User newUser = new User();

		newUser.setUserName(username);
		newUser.setPassword(md5Password);
		newUser.setCreateDate(LocalDateTime.now());
		newUser.setUpdateDate(LocalDateTime.now());
		newUser.setStatus(1);

		userMapper.add(newUser);


	}

	@Override
	public UserVO login(String username, String password) {

		User user = userMapper.getUserByUserName(username);
		if (user == null) {
			throw new IllegalArgumentException("用户名或密码错误");
		}
		if (!user.getPassword().equals(Md5Util.getMD5String(password))) {
			throw new IllegalArgumentException("用户名或密码错误");
		}

		if (user.getStatus() == 0) {
			throw new IllegalArgumentException("用户已被禁用");
		}

//		进行jwt token的生成

		HashMap<String, Object> claims = new HashMap<>();
		claims.put(JwtClaimsConstant.USER_ID, user.getUserId());
		String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
				jwtProperties.getUserTtl(),
				claims);

		UserVO userVO = new UserVO();
		userVO.setUserId(user.getUserId());
		userVO.setUserName(user.getUserName());
		userVO.setToken(token);
		return userVO;

	}

	@Override
	public void updateUserInfo(UserDTO userDTO) {


		User userById = userMapper.getUserById(UserContext.getUser().intValue());

		if (userById == null) {
			throw new IllegalArgumentException("用户不存在");
		}

//		判断邮箱和手机号是否已被注册

		List<User> users = userMapper.getAll();

//		循环遍历所有用户，判断邮箱和手机号是否已被注册
		for (User user : users) {
			if (user.getEmail() != null && user.getEmail().equals(userDTO.getEmail()) && user.getUserId() != userById.getUserId()) {
				throw new IllegalArgumentException("邮箱已被他人注册");
			}
			if (user.getPhoneNumber() != null && user.getPhoneNumber().equals(userDTO.getPhoneNumber()) && user.getUserId() != userById.getUserId()) {
				throw new IllegalArgumentException("手机号已被他人注册");
			}
		}


		userById.setEmail(userDTO.getEmail());
		userById.setPhoneNumber(userDTO.getPhoneNumber());
		userById.setUpdateDate(LocalDateTime.now());

		userMapper.update(userById);


	}

	@Override
	public void updateUserAvatar(String avatarUrl) {


		int userId = UserContext.getUser().intValue();

		User user = new User();
		user.setUserId(userId);
		user.setUserPic(avatarUrl);
		user.setUpdateDate(LocalDateTime.now());


		userMapper.update(user);


	}

	@Override
	public void recharge(BigDecimal amount) {

		User user = userMapper.getUserById(UserContext.getUser().intValue());

		if (user == null) {
			throw new IllegalArgumentException("用户不存在");
		}

		user.setAccountBalance(user.getAccountBalance().add(amount));

		userMapper.update(user);

	}
}
